24. Exercise: Data Messages

L1 A24 Data Messages

Exercise

  1. In order to handle FCM messages, you need to handle the data payload in the onMessageReceived() function of MyFirebaseMessagingService. The data payload is stored in the data property of the remoteMessage object. Both remoteMessage object and the data property can be null. Check if data property of remoteMessage object has some value and print the data to the log.



  2. Add a log to print data property of the remoteMessage object after checking remoteMessage and data is not empty.
// MyFirebaseMessagingService.kt

    // [START receive_message]
    override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: ${remoteMessage?.from}")

       // TODO: Step 3.5 check messages for data
        // Check if message contains a data payload.
        remoteMessage?.data?.let {
            Log.d(TAG, "Message data payload: " + remoteMessage.data)
        }

    }
    // [END receive_message]
  1. To test your code, you can use the Notifications composer again, this time setting Custom data key, value pairs under Additional options in Step 4. Create a new message and select the same topic. Set eggs and 3 as custom data.

  1. Make sure your app is running and in foreground. Send the message and observe data message log in the logcat.

If your app is in the background, the FCM message will trigger an automatic notification and onMessageReceived function will receive the remoteMessage object only when the user clicks the notification.